<template>
  <div class="singer" ref="singer">
    <list-view :data="this.singers" @select="selectSinger" ref="list"></list-view>
    <router-view></router-view>
  </div>
</template>

<script type="text/javascript">
import { getSingers } from '@/api/singer'
import { ERR_OK } from '@/common/js/common'
import pinyin from '@/common/js/vue-py'
import Singer from '@/common/js/sing'
import ListView from '@/base/listview/listview'
import { mapMutations } from 'vuex'
import { playlistMixin } from '@/common/js/mixin'

const HOT_NAME = '热门'
const HOT_SINGERS = 10

export default {
  mixins: [playlistMixin],
  data () {
    return {
      // 歌手数据
      singers: []
    }
  },
  methods: {
    // 获取子组件传入的值
    selectSinger (singer) {
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer)
      console.log(singer)
      console.log(2)
    },
    _getSingers () {
      getSingers().then((res) => {
        if (res.status === ERR_OK) {
          var s = res.data.artists
          s.map((item) => {
            item.initial = pinyin.chineseToPinYin(item.name).toUpperCase()
          })
          this.singers = this._normalizeSinger(s)
          // console.log(this.singers)
          // console.log(res)
        }
      })
    },
    // 获取歌手需要内容
    _normalizeSinger (list) {
      var map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      // console.log(map.hot.title)
      list.forEach((item, index) => {
        if (index < HOT_SINGERS) {
          map.hot.items.push(new Singer({
            id: item.id,
            name: item.name,
            avatar: item.img1v1Url,
            aliaName: item.alias.join(' / ')
          }))
        }
        var key = item.initial
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer({
          id: item.id,
          name: item.name,
          avatar: item.img1v1Url,
          aliaName: item.alias[0]
        }))
      })
      var hot = []
      var ret = []
      for (const key in map) {
        var val = map[key]
        if (val.title.match(/[A-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(ret)
    },
    handlePlaylist (playlist) {
      const bottom = playlist.length > 0 ? '60px' : ''
      this.$refs.singer.style.bottom = bottom
      this.$refs.list.refresh()
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  created () {
    this._getSingers()
    // console.log(pinyin.chineseToPinYin('订单').toUpperCase())
  },
  components: {
    ListView
  }
}

</script>

<style lang="less" scoped>
.singer {
  position: fixed;
  top: 80px;
  bottom: 0;
  width: 100%;
  /*padding-top: relative;*/
}
</style>
